<template>
  <div class="app-container">
    <!--搜索栏-->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="关键字搜索" label-width="85" prop="keyValue">
        <el-input
          v-model="queryParams.keyValue"
          placeholder="请输入搜索关键字"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="风险分析单元" label-width="100">
        <el-tree-select
          v-model="queryParams.riskUnitId"
          :data="unitOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }"
          placeholder="请选择风险分析单元"
          filterable
        >
          <template
            class="custom-tree-node"
            #default="{ node, data }"
            :disabled="data.nodeLevel == '1'"
          >
            <span>{{ node.label }}</span>
          </template>
        </el-tree-select>
      </el-form-item>
      <el-form-item label="风险等级" label-width="70">
        <el-select
          v-model="queryParams.riskLevelId"
          placeholder="请选择"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in riskLevelOptions"
            :key="dict.riskLevelId"
            :label="dict.riskLevelName"
            :value="dict.riskLevelId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="风险评估方法" label-width="100" prop="level">
        <el-select
          v-model="queryParams.determineMethodType"
          placeholder="请选择风险评估方法"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in methodSelectOptions"
            :key="dict.id"
            :label="dict.label"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="可能导致事故" label-width="100">
        <el-select
          v-model="queryParams.accidentTypeId"
          placeholder="请选择"
          multiple
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in accidentTypeOptions"
            :key="dict.accidentTypeId"
            :label="dict.accidentTypeName"
            :value="dict.accidentTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--操作栏-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['risk:event:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <!--数据列表-->
    <el-table v-loading="loading" :data="riskList">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column
        label="风险事件名称"
        prop="riskEventName"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="风险分析单元"
        prop="riskUnitName"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="可导致事故类型" prop="accidentTypeName" width="160" />
      <el-table-column
        label="风险描述"
        prop="riskDescription"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="风险评估方法" prop="determineMethodName" width="160" />
      <el-table-column label="风险等级" prop="riskLevelName" width="160" />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['risk:event:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['risk:event:remove']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="详情" placement="top">
            <el-button
              link
              type="primary"
              icon="CircleCheck"
              @click="handleInfo(scope.row)"
              v-hasPermi="['risk:event:query']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.current"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />
    <!--新增或者修改风险事件对话框-->
    <el-dialog
      :title="title"
      v-model="open"
      width="60%"
      append-to-body
      close="closeDialog"
    >
      <el-tabs
        v-model="activeTabName"
        type="card"
        class="demo-tabs"
        @tab-click="handleClick"
      >
        <el-tab-pane label="风险辨识" name="1">
          <el-form
            ref="eventRef"
            :model="riskForm"
            :rules="rules"
            style="margin-top: 18px"
          >
            <el-form-item label="风险分析单元:" label-width="140px" prop="riskUnitId">
              <el-tree-select
                v-model="riskForm.riskUnitId"
                :data="unitOptions"
                ref="measureSelect"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="classfyId"
                placeholder="请选择风险分析单元"
                filterable
              >
                <template
                  class="custom-tree-node"
                  #default="{ node, data }"
                  :disabled="data.nodeLevel == '1'"
                >
                  <span>{{ node.label }}</span>
                </template>
              </el-tree-select>
            </el-form-item>
            <el-form-item label="风险事件:" label-width="140px" prop="riskEventName">
              <el-input
                v-model="riskForm.riskEventName"
                placeholder="请输入风险事件名称"
              />
            </el-form-item>
            <el-form-item label="风险描述:" label-width="140px" prop="riskDescription">
              <el-input
                type="textarea"
                :rows="3"
                v-model="riskForm.riskDescription"
                placeholder="请输入管控措施"
                maxlength="3000"
              />
            </el-form-item>
            <el-form-item
              label="可导致的事故类型:"
              label-width="140px"
              prop="accidentTypeId"
            >
              <el-checkbox-group v-model="riskForm.accidentTypeId">
                <el-checkbox
                  v-for="item in accidentTypeOptions"
                  :key="item.accidentTypeId"
                  :label="item.accidentTypeId"
                >
                  {{ item.accidentTypeName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="风险评估" name="2">
          <el-form
            ref="methodRef"
            :model="riskForm.riskEstimateMethod"
            :rules="rules"
            style="margin-top: 18px"
          >
            <el-form-item label="风险判定方法:" label-width="140px" prop="methodType">
              <el-radio-group v-model="riskForm.riskEstimateMethod.methodType">
                <el-radio label="6" size="large" border>JSA判定</el-radio>
                <el-radio label="3" size="large" border>LS评估</el-radio>
                <el-radio label="2" size="large" border>LEC评估</el-radio>
                <el-radio label="4" size="large" border>LC评估</el-radio>
                <el-radio label="5" size="large" border>MES评估</el-radio>
                <el-radio label="1" size="large" border>直接判定</el-radio>
              </el-radio-group>
            </el-form-item>
            <!--评估方法核心-->
            <el-form-item
              label="可能性:"
              label-width="140px"
              prop="likelihood"
              v-if="likehoodShow"
            >
              <el-select
                v-model="riskForm.riskEstimateMethod.likelihood"
                placeholder="请选择"
                @change="likehoodChange"
              >
                <el-option
                  v-for="dict in likehoodOptions"
                  :key="dict.methodParamsId"
                  :label="dict.paramsDescription"
                  :value="dict.paramsValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="控制措施状态:"
              label-width="140px"
              prop="measureStatus"
              v-if="controlStatusShow"
            >
              <el-select
                v-model="riskForm.riskEstimateMethod.measureStatus"
                placeholder="请选择"
                @change="controlStatusChange"
              >
                <el-option
                  v-for="dict in controlStatusOptions"
                  :key="dict.methodParamsId"
                  :label="dict.paramsDescription"
                  :value="dict.paramsValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="暴露率/频次:"
              label-width="140px"
              prop="exposureRate"
              v-if="exposureShow"
            >
              <el-select
                v-model="riskForm.riskEstimateMethod.exposureRate"
                placeholder="请选择"
                @change="exposureRateChange"
              >
                <el-option
                  v-for="dict in exposureOptions"
                  :key="dict.methodParamsId"
                  :label="dict.paramsDescription"
                  :value="dict.paramsValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="后果:"
              label-width="140px"
              prop="seriousness"
              v-if="seriousnessShow"
            >
              <el-select
                v-model="riskForm.riskEstimateMethod.seriousness"
                placeholder="请选择"
                @change="seriousnessChange"
              >
                <el-option
                  v-for="dict in seriousnessOptions"
                  :key="dict.methodParamsId"
                  :label="dict.paramsDescription"
                  :value="dict.paramsValue"
                />
              </el-select>
            </el-form-item>
            <el-col :span="6">
              <el-form-item
                label="风险值:"
                label-width="140px"
                prop="riskValue"
                v-if="riskValueShow"
              >
                <el-input
                  v-model="riskForm.riskEstimateMethod.riskValue"
                  ref="riskValueRef"
                  placeholder="风险值"
                  width="80px"
                  disabled
                />
              </el-form-item>
            </el-col>
            <!--评估方法核心-->
            <el-form-item label="风险等级:" label-width="140px" prop="riskLevelId">
              <el-select
                v-model="riskForm.riskEstimateMethod.riskLevelId"
                placeholder="请选择"
                :disabled="isDisabled"
              >
                <el-option
                  v-for="dict in riskLevelOptions"
                  :key="dict.riskLevelId"
                  :label="dict.riskLevelName"
                  :value="dict.riskLevelId"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="管控措施" name="3">
          <el-form
            ref="measureRef"
            :model="riskForm.riskEventMeasureList"
            :rules="rules"
            style="margin-top: 18px"
          >
            <el-row class="demo-radius" v-for="index of riskMeasureNum" :key="index">
              <el-col :span="20">
                <el-form-item label="管控措施:" label-width="140px">
                  <el-tree-select
                    style="width: 90%"
                    v-model="riskForm.riskEventMeasureList[index - 1].riskMeasureId"
                    check-strictly
                    :data="measureClassFyOptions"
                    ref="measureSelect"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children',
                      disabled: 'disabled',
                    }"
                    value-key="id"
                    placeholder="请选择管控措施内容"
                    filterable
                  >
                    <template class="custom-tree-node" #default="{ node, data }">
                      <div
                        style="
                          display: flex;
                          align-items: flex-start;
                          justify-content: space-between;
                          width: 100%;
                        "
                      >
                        <span style="padding-left: 4px">{{ node.label }}</span>
                      </div>
                    </template>
                  </el-tree-select>
                </el-form-item>
              </el-col>
              <el-col :span="4" style="display: flex; align-items: center">
                <el-form-item>
                  <el-button
                    v-if="index !== 1"
                    icon="Delete"
                    @click="deleteMeasureNum(index)"
                  ></el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="demo-add">
              <el-button type="primary" icon="Plus" @click="addMeasureNum"
                >新增</el-button
              >
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div v-if="showSubmit" class="dialog-footer">
          <el-button @click="nextTab('up')">上一步</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-else class="dialog-footer">
          <el-button v-if="activeTabName == '2'" @click="nextTab('up')">上一步</el-button>
          <el-button type="primary" @click="nextTab('down')">下一步</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Risk">
import { listRiskLevel } from "@/api/prevent/risk/riskLevel";
import { listAccidentType } from "@/api/prevent/risk/accidentType";
import { listMethodParams } from "@/api/prevent/risk/params";
import { getUnitTree } from "@/api/prevent/risk/unit";
import { listMeasureClassFy } from "@/api/prevent/risk/classfy";
import { getMeasureAndClassFyTree } from "@/api/prevent/risk/classfy";
import { getMeasureOptions } from "@/api/prevent/risk/measure";
import {
  listRiskEvent,
  addRiskEvent,
  deleteRiskEvent,
  updateRiskEvent,
  getRiskEvent,
} from "@/api/prevent/risk/riskEvent";
const { proxy } = getCurrentInstance();
const activeTabName = ref("1");
const title = ref(""); //对话框标题
const riskList = ref([]);
// const checkList = ref([]);
// const single = ref(true);
// const multiple = ref(true);
const showSubmit = ref(false);
const open = ref(false);
const isDisabled = ref(false);
const total = ref(0);
const methodSelectOptions = ref([
  { id: "1", label: "直接判定" },
  { id: "2", label: "LEC评估" },
  { id: "3", label: "LS评估" },
  { id: "4", label: "LC评估" },
  { id: "5", label: "MES评估" },
  { id: "6", label: "JSA判定" },
]); //风险评估方法选择项
const measureOptions = ref([]); //管控措施选择项
const measureClassFyOptions = ref([]); //管控措施类型选择项
const unitOptions = ref([]); //风险分析单元选择项
const riskLevelOptions = ref([]); //风险等级数据
const accidentTypeOptions = ref([]); //可导致风险事故类型
const methodParamsOptions = ref([]); //风险评估方法参数
const likehoodOptions = ref([]); //可能性参数
const seriousnessOptions = ref([]); //后果参数
const exposureOptions = ref([]); //暴露率参数
const controlStatusOptions = ref([]); //控制措施状态参数
const likehoodShow = ref(false); //可能性显示
const seriousnessShow = ref(false); //后果显示
const exposureShow = ref(false); //暴露率显示
const controlStatusShow = ref(false); //控制措施状态显示
const riskValueShow = ref(true); //风险值显示
//实时值
const likehoodRuntimeVal = ref("0"); //可能性显示
const seriousnessRuntimeVal = ref("0"); //后果显示
const exposureRuntimeVal = ref("0"); //暴露率显示
const controlStatusRuntimeVal = ref("0"); //控制措施状态显示
const riskValueRuntimeVal = ref("0"); //风险值实时呈现
//const methodParamsOptions = ref([]);

const loading = ref(true);
const riskMeasureNum = ref(1);
const router = useRouter();
const updateData = ref({}); //编辑的数据备份

const data = reactive({
  riskForm: {
    determineMethodType: "",
    accidentTypeId: [],
    riskEventMeasureList: [
      {
        riskMeasureId: undefined,
        measureClassfyId: undefined,
        riskMeasureDesc: undefined,
      },
    ],
    riskEstimateMethod: {
      riskValue: riskValueRuntimeVal.value,
      riskLevelId: undefined,
      likelihood: "",
      seriousness: "",
      measureStatus: "",
      exposureRate: "",
      methodType: undefined,
    },
  },
  queryParams: {
    current: 1,
    size: 10,
    keyValue: undefined,
    riskLevelId: undefined,
    riskUnitId: undefined,
    determineMethodType: undefined,
  },
  rules: {
    riskUnitId: [{ required: true, message: "风险分析单元必须选择", trigger: "change" }],
    riskEventName: [{ required: true, message: "风险事件必须填写", trigger: "blur" }],
    accidentTypeId: [
      { required: true, message: "可导致的事故类型必须选择", trigger: "change" },
    ],
    riskDescription: [{ required: true, message: "风险描述必须填写", trigger: "blur" }],
    methodType: [{ required: true, message: "风险评估方法必须选择", trigger: "change" }],
    likelihood: [{ required: true, message: "可能性必须选择", trigger: "change" }],
    measureStatus: [
      { required: true, message: "控制措施状态必须选择", trigger: "change" },
    ],
    exposureRate: [{ required: true, message: "暴露率必须选择", trigger: "change" }],
    seriousness: [{ required: true, message: "后果严重性必须选择", trigger: "change" }],
    riskValue: [{ required: true, message: "风险值必须计算", trigger: "change" }],
    riskLevelId: [{ required: true, message: "风险等级必须选择", trigger: "change" }],
  },
});

const { queryParams, riskForm, rules } = toRefs(data);

/** 数据监听  评估方法的变化*/
watch(
  () => riskForm.value.riskEstimateMethod.methodType,
  (newValue, oldValue) => {
    // console.log(newValue, oldValue);
    // console.log("update的数据：", updateData.value);
    clearMeathodFormData(); //清楚表单数据
    if (
      updateData.value != null &&
      newValue == updateData.value.methodType &&
      oldValue != undefined
    ) {
      //当更新时，切换回原来的
      riskForm.value.riskEstimateMethod.exposureRate = updateData.value.exposureRate;
      riskForm.value.riskEstimateMethod.likelihood = updateData.value.likelihood;
      riskForm.value.riskEstimateMethod.seriousness = updateData.value.seriousness;
      riskForm.value.riskEstimateMethod.measureStatus = updateData.value.measureStatus;
      riskForm.value.riskEstimateMethod.riskLevelId = updateData.value.riskLevelId;
      riskForm.value.riskEstimateMethod.riskValue = updateData.value.riskValue;
    }
    resetCompute();
    riskForm.value.determineMethodType = newValue;
    clearOptionsAndShow();
    changeMethodsOptions();
  }
);
/** 清空method Form表单 */
function clearMeathodFormData() {
  riskForm.value.riskEstimateMethod.exposureRate = "";
  riskForm.value.riskEstimateMethod.likelihood = "";
  riskForm.value.riskEstimateMethod.seriousness = "";
  riskForm.value.riskEstimateMethod.measureStatus = "";
  riskForm.value.riskEstimateMethod.riskLevelId = "";
  riskForm.value.riskEstimateMethod.riskValue = "";
}

/** 数据监听 */
watch(
  () => open.value,
  (newValue, oldValue) => {
    console.log("弹窗", newValue);
    if (newValue == false && riskForm.value.riskEventId != null) {
      cancel();
    }
  }
);
/** 监听风险评估方法变化 */
watch(
  () => riskForm.value.riskEstimateMethod.riskLevelId,
  (newVal, oldVal) => {
    if (newVal != undefined) {
      riskForm.value.riskLevelId = riskForm.value.riskEstimateMethod.riskLevelId;
    }
  }
);

/** 对话框切换下一步 */
function nextTab(flag) {
  if (activeTabName.value == "1") {
    proxy.$refs["eventRef"].validate((valid) => {});
    setTimeout(() => {
      activeTabName.value = "2";
    }, 500);
  } else if (activeTabName.value == "2") {
    if (flag == "up") {
      activeTabName.value = "1";
    } else {
      proxy.$refs["methodRef"].validate((valid) => {});
      setTimeout(() => {
        activeTabName.value = "3";
        showSubmit.value = true;
      }, 500);
    }
  } else {
    showSubmit.value = false;
    activeTabName.value = "2";
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 获取风险事件列表 */
function getList() {
  loading.value = true;
  listRiskEvent(queryParams.value).then((response) => {
    riskList.value = response.data.dataList;
    total.value = response.data.totalNum;
    loading.value = false;
  });
}
/** 重置表单 */
function reset() {
  //console.log("调用了全局reset方法")
  riskForm.value = {
    determineMethodType: undefined,
    accidentTypeId: [],
    riskEventMeasureList: [
      {
        riskMeasureId: undefined,
      },
    ],
    riskEstimateMethod: {
      riskValue: riskValueRuntimeVal.value,
      riskLevelId: undefined,
      likelihood: "",
      seriousness: "",
      measureStatus: "",
      exposureRate: "",
      methodType: "",
    },
  };
  proxy.resetForm("eventRef");
  proxy.resetForm("methodRef");
  proxy.resetForm("measureRef");
  activeTabName.value = "1";
  riskMeasureNum.value = 1;
  //initMethod();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    current: 1,
    size: 10,
  };
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 添加风险清单 */
function handleAdd() {
  reset();
  initMethod();
  open.value = true;
  title.value = "新增风险清单";
  updateData.value = null;
}
/** 验证常规数据 */
function volidateForm() {
  if (riskForm.value.riskUnitId == "" || riskForm.value.riskUnitId == undefined) {
    proxy.$modal.msgError("请选择风选分析单元！");
    return;
  }
  if (riskForm.value.riskEventName == "" || riskForm.value.riskEventName == undefined) {
    proxy.$modal.msgError("风险事件名称需要填写！");
    return;
  }
  if (riskForm.value.accidentTypeId == "" || riskForm.value.accidentTypeId == undefined) {
    proxy.$modal.msgError("请选择可导致的事故类型");
    return;
  }
  if (
    riskForm.value.riskDescription == "" ||
    riskForm.value.riskDescription == undefined
  ) {
    proxy.$modal.msgError("请填写风险描述！");
    return;
  }
  if (riskForm.value.determineMethodType == "1") {
    if (riskForm.value.riskLevelId == "" || riskForm.value.riskLevelId == undefined) {
      proxy.$modal.msgError("请选择风险等级！");
      return;
    }
  } else if (riskForm.value.determineMethodType == "2") {
    //LEC
    if (
      riskForm.value.riskEstimateMethod.likelihood == "" ||
      riskForm.value.riskEstimateMethod.likelihood == undefined
    ) {
      proxy.$modal.msgError("请选择LEC评估方法的可能性！");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.exposureRate == "" ||
      riskForm.value.riskEstimateMethod.exposureRate == undefined
    ) {
      proxy.$modal.msgError("请选择LEC评估方法的暴露率!");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.seriousness == "" ||
      riskForm.value.riskEstimateMethod.seriousness == undefined
    ) {
      proxy.$modal.msgError("请选择LEC评估方法的后果！");
      return;
    }
  } else if (riskForm.value.determineMethodType == "3") {
    //LS
    if (
      riskForm.value.riskEstimateMethod.likelihood == "" ||
      riskForm.value.riskEstimateMethod.likelihood == undefined
    ) {
      proxy.$modal.msgError("请选择LS评估方法的可能性！");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.seriousness == "" ||
      riskForm.value.riskEstimateMethod.seriousness == undefined
    ) {
      proxy.$modal.msgError("请选择LS评估方法的后果！");
      return;
    }
  } else if (riskForm.value.determineMethodType == "4") {
    //LC
    if (
      riskForm.value.riskEstimateMethod.likelihood == "" ||
      riskForm.value.riskEstimateMethod.likelihood == undefined
    ) {
      proxy.$modal.msgError("请选择LC评估方法的可能性！");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.seriousness == "" ||
      riskForm.value.riskEstimateMethod.seriousness == undefined
    ) {
      proxy.$modal.msgError("请选择LC评估方法的后果！");
      return;
    }
  } else if (riskForm.value.determineMethodType == "5") {
    //MES
    if (
      riskForm.value.riskEstimateMethod.measureStatus == "" ||
      riskForm.value.riskEstimateMethod.measureStatus == undefined
    ) {
      proxy.$modal.msgError("请选择MES评估方法的控制状态！");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.exposureRate == "" ||
      riskForm.value.riskEstimateMethod.exposureRate == undefined
    ) {
      proxy.$modal.msgError("请选择MES评估方法的暴露率!");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.seriousness == "" ||
      riskForm.value.riskEstimateMethod.seriousness == undefined
    ) {
      proxy.$modal.msgError("请选择MES评估方法的后果！");
      return;
    }
  } else if (riskForm.value.determineMethodType == "6") {
    //JSA
    if (
      riskForm.value.riskEstimateMethod.likelihood == "" ||
      riskForm.value.riskEstimateMethod.likelihood == undefined
    ) {
      proxy.$modal.msgError("请选择JSA评估方法的可能性！");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.exposureRate == "" ||
      riskForm.value.riskEstimateMethod.exposureRate == undefined
    ) {
      proxy.$modal.msgError("请选择JSA评估方法的暴露率!");
      return;
    }
    if (
      riskForm.value.riskEstimateMethod.seriousness == "" ||
      riskForm.value.riskEstimateMethod.seriousness == undefined
    ) {
      proxy.$modal.msgError("请选择JSA评估方法的后果！");
      return;
    }
  } else {
    proxy.$modal.msgError("请选择风险评估方法！");
    return;
  }
  return true;
}
/** 验证管控措施 */
function volidateMeasure() {
  let result = true;
  riskForm.value.riskEventMeasureList.forEach((item, index) => {
    if (item.riskMeasureId == "" || item.riskMeasureId == undefined) {
      result = false;
      proxy.$modal.msgError("第" + (index + 1) + "项：请选择管控措施内容！");
    }
  });
  if (!result) {
    return;
  } else {
    return true;
  }
}
/** 提交按钮 */
function submitForm() {
  if (!volidateForm() || !volidateMeasure()) {
    return;
  }
  if (riskForm.value.riskEventId != undefined) {
    console.log("修改");
    riskForm.value.accidentTypeId = riskForm.value.accidentTypeId + "";
    updateRiskEvent(riskForm.value).then((response) => {
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getList();
    });
  } else {
    riskForm.value.accidentTypeId = riskForm.value.accidentTypeId + "";
    riskForm.value.riskLevelId = riskForm.value.riskEstimateMethod.riskLevelId;
    console.log(riskForm.value);
    addRiskEvent(riskForm.value).then((response) => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
    });
  }
}
/** 取消按钮 */
function cancel() {
  //console.log("cancel")
  open.value = false;
  reset();
  //initMethod();
}

/** 删除按钮 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除风险清单的数据项？")
    .then(function () {
      return deleteRiskEvent(row.riskEventId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 更新按钮 */
function handleUpdate(row) {
  reset();
  getRiskEvent(row.riskEventId).then((response) => {
    riskForm.value = response.data;
    riskForm.value.accidentTypeId = riskForm.value.accidentTypeId.split(",").map(Number);
    riskForm.value.riskEstimateMethod = response.data.riskEstimateMethod;
    riskForm.value.riskEstimateMethod.methodType =
      response.data.riskEstimateMethod.methodType + "";
    response.data.riskEventMeasureList.forEach((item, index) => {
      response.data.riskEventMeasureList[index].riskMeasureId =
        response.data.riskEventMeasureList[index].riskMeasureId + "";
    });
    riskForm.value.riskEventMeasureList = response.data.riskEventMeasureList;

    riskMeasureNum.value = response.data.riskEventMeasureList.length;
    open.value = true;
    title.value = "修改风险清单";
    updateData.value = JSON.parse(JSON.stringify(response.data.riskEstimateMethod));
    //console.log("获取数据完成");
  });
}
/** 详情按钮 */
function handleInfo(row) {
  router.push("/prevent/risk/info/" + row.riskEventId);
}

/** --------------对话框----------------- */
/** 重置评估方法 */
function resetMethod() {
  console.log("调用了resetMethod");
  riskForm.value.riskEstimateMethod = {
    riskLevelId: undefined,
    likelihood: "",
    seriousness: "",
    riskValue: riskValueRuntimeVal.value,
    measureStatus: "",
    exposureRate: "",
    methodType: "",
  };
  proxy.resetForm("methodRef");
  clearOptionsAndShow();
}
/** 清楚选项值 */
function clearOptionsAndShow() {
  likehoodOptions.value = []; //可能性参数
  seriousnessOptions.value = []; //后果参数
  exposureOptions.value = []; //暴露率参数
  controlStatusOptions.value = []; //控制措施状态参数
  likehoodShow.value = false; //可能性显示
  seriousnessShow.value = false; //后果显示
  exposureShow.value = false; //暴露率显示
  controlStatusShow.value = false; //控制措施状态显示
}
/** 处理新增风险切换 */
const handleClick = (tab, event) => {
  if (tab.props.name == "3") {
    showSubmit.value = true;
  } else {
    showSubmit.value = false;
  }
  //console.log(tab,event)
};
/** 初始化风险评估方法 */
function initMethod() {
  // console.log("调用initMethod------");
  resetMethod();
  riskValueShow.value = true;
  isDisabled.value = true;
}

/** 更新评估方法的参数选项 */
function changeMethodsOptions() {
  if (riskForm.value.riskEstimateMethod.methodType == "1") {
    isDisabled.value = false;
    riskValueShow.value = false;
  } else if (riskForm.value.riskEstimateMethod.methodType == "2") {
    riskValueShow.value = true;
    methodParamsOptions.value.filter((item) => {
      if (item.paramsType == "LEC-L") {
        likehoodOptions.value.push(item);
        likehoodShow.value = true;
      } else if (item.paramsType == "LEC-E") {
        exposureOptions.value.push(item);
        exposureShow.value = true;
      } else if (item.paramsType == "LEC-C") {
        seriousnessOptions.value.push(item);
        seriousnessShow.value = true;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "3") {
    riskValueShow.value = true;
    methodParamsOptions.value.filter((item) => {
      if (item.paramsType == "LS-L") {
        likehoodOptions.value.push(item);
        likehoodShow.value = true;
      } else if (item.paramsType == "LS-S") {
        seriousnessOptions.value.push(item);
        seriousnessShow.value = true;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "4") {
    riskValueShow.value = true;
    methodParamsOptions.value.filter((item) => {
      if (item.paramsType == "LC-L") {
        likehoodOptions.value.push(item);
        likehoodShow.value = true;
      } else if (item.paramsType == "LC-C") {
        seriousnessOptions.value.push(item);
        seriousnessShow.value = true;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "5") {
    riskValueShow.value = true;
    methodParamsOptions.value.filter((item) => {
      if (item.paramsType == "MES-M") {
        controlStatusOptions.value.push(item);
        controlStatusShow.value = true;
      } else if (item.paramsType == "MES-E") {
        exposureOptions.value.push(item);
        exposureShow.value = true;
      } else if (item.paramsType == "MES-S") {
        seriousnessOptions.value.push(item);
        seriousnessShow.value = true;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "6") {
    riskValueShow.value = true;
    methodParamsOptions.value.filter((item) => {
      if (item.paramsType == "JSA-L") {
        likehoodOptions.value.push(item);
        likehoodShow.value = true;
      } else if (item.paramsType == "JSA-E") {
        exposureOptions.value.push(item);
        exposureShow.value = true;
      } else if (item.paramsType == "JSA-S") {
        seriousnessOptions.value.push(item);
        seriousnessShow.value = true;
      }
    });
  }
}

/** 获取管控措施类型及内容列表数据 */
function getRiskMeasureClassfyList() {
  getMeasureAndClassFyTree().then((response) => {
    measureClassFyOptions.value = response.data;
  });
}
/** 获取风险等级列表数据 */
function getRiskLevelList() {
  listRiskLevel().then((response) => {
    riskLevelOptions.value = response.data;
  });
}
/** 获取风险等级列表数据 */
function getRiskUnitList() {
  getUnitTree().then((response) => {
    unitOptions.value = response.data;
  });
}

/** 获取可导致事故类型列表 */
function getAccidentTypeList() {
  listAccidentType().then((response) => {
    accidentTypeOptions.value = response.data;
  });
}
/** 获取风险评估方法参数 */
function getMethodParamsList() {
  listMethodParams().then((response) => {
    methodParamsOptions.value = response.data;
    initMethod();
  });
}

watch(
  [
    likehoodRuntimeVal,
    seriousnessRuntimeVal,
    exposureRuntimeVal,
    controlStatusRuntimeVal,
  ],
  (newVal, oldVal) => {
    if (
      riskForm.value.riskEstimateMethod.methodType == "2" ||
      riskForm.value.riskEstimateMethod.methodType == "6"
    ) {
      // LEC或JSA
      if (
        likehoodRuntimeVal.value !== "0" &&
        exposureRuntimeVal.value !== "0" &&
        seriousnessRuntimeVal.value !== "0"
      ) {
        riskForm.value.riskEstimateMethod.riskValue = parseFloat(
          likehoodRuntimeVal.value *
            exposureRuntimeVal.value *
            seriousnessRuntimeVal.value
        );

        changeRiskLevelByRiskValue();
      }
    } else if (
      riskForm.value.riskEstimateMethod.methodType == "3" ||
      riskForm.value.riskEstimateMethod.methodType == "4"
    ) {
      // LC或LS
      if (likehoodRuntimeVal.value !== "0" && seriousnessRuntimeVal.value !== "0") {
        riskForm.value.riskEstimateMethod.riskValue =
          likehoodRuntimeVal.value * seriousnessRuntimeVal.value;
        changeRiskLevelByRiskValue();
      }
    } else if (riskForm.value.riskEstimateMethod.methodType == "5") {
      // MES
      if (
        controlStatusRuntimeVal.value !== "0" &&
        exposureRuntimeVal.value !== "0" &&
        seriousnessRuntimeVal.value !== "0"
      ) {
        riskForm.value.riskEstimateMethod.riskValue = parseFloat(
          controlStatusRuntimeVal.value *
            exposureRuntimeVal.value *
            seriousnessRuntimeVal.value
        );
        changeRiskLevelByRiskValue();
      }
    }
  }
);
/** 清楚风险评估方法计算数据 */
function resetCompute() {
  likehoodRuntimeVal.value = "0"; //可能性显示
  seriousnessRuntimeVal.value = "0"; //后果显示
  exposureRuntimeVal.value = "0"; //暴露率显示
  controlStatusRuntimeVal.value = "0"; //控制措施状态显示
  riskValueRuntimeVal.value = "0"; //风险值实时呈现
}
/** 监听风险评估方法值得变化 */
function likehoodChange(val) {
  //console.log('likehood',val)
  likehoodRuntimeVal.value = val;
}
function controlStatusChange(val) {
  //console.log('controlStatus',val)
  controlStatusRuntimeVal.value = val;
}
function seriousnessChange(val) {
  //console.log('seriousness',val)
  seriousnessRuntimeVal.value = val;
}
function exposureRateChange(val) {
  //console.log('exposureRate',val)
  exposureRuntimeVal.value = val;
}

/** 通过风险值来判断风险等级 */
function changeRiskLevelByRiskValue() {
  const computeValue = riskForm.value.riskEstimateMethod.riskValue;
  //riskForm.value.riskLevelId =1;
  if (riskForm.value.riskEstimateMethod.methodType == "2") {
    riskLevelOptions.value.filter((item) => {
      if (item.lecMaxValue >= computeValue && item.lecMinValue <= computeValue) {
        riskForm.value.riskEstimateMethod.riskLevelId = item.riskLevelId;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "3") {
    riskLevelOptions.value.filter((item) => {
      if (item.lsMaxValue >= computeValue && item.lsMinValue <= computeValue) {
        riskForm.value.riskEstimateMethod.riskLevelId = item.riskLevelId;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "4") {
    riskLevelOptions.value.filter((item) => {
      if (item.lcMaxValue >= computeValue && item.lcMinValue <= computeValue) {
        riskForm.value.riskEstimateMethod.riskLevelId = item.riskLevelId;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "5") {
    riskLevelOptions.value.filter((item) => {
      if (item.mesMaxValue >= computeValue && item.mesMinValue <= computeValue) {
        riskForm.value.riskEstimateMethod.riskLevelId = item.riskLevelId;
      }
    });
  } else if (riskForm.value.riskEstimateMethod.methodType == "6") {
    riskLevelOptions.value.filter((item) => {
      if (item.jsaMaxValue >= computeValue && item.jsaMinValue <= computeValue) {
        riskForm.value.riskEstimateMethod.riskLevelId = item.riskLevelId;
      }
    });
  } else {
    riskForm.value.riskLevelId = riskForm.value.riskEstimateMethod.riskLevelId;
  }
}
/** 添加风险的管控措施 */
function addMeasureNum() {
  riskForm.value.riskEventMeasureList.push({
    riskMeasureId: undefined,
    measureClassfyId: undefined,
  });
  riskMeasureNum.value++;
}
/** 删除当前的管控措施 */
function deleteMeasureNum(index) {
  if (riskMeasureNum.value > 1) {
    riskForm.value.riskEventMeasureList.splice(index - 1, 1);
    riskMeasureNum.value--;
  }
}

/** 初始化调用 */
getRiskLevelList();
getList();
getAccidentTypeList();
getMethodParamsList();
getRiskUnitList();
getRiskMeasureClassfyList();
</script>
<style>
/* .is-active{
    background-color: #1989FA;
    color:#FFFFFF !important;
} */
.demo-radius {
  width: 90%;
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
  margin: 20px;
  padding: 20px;
}
.demo-add {
  width: 90%;
  margin: 20px;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
</style>
